'use client';

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import PromptInput from "../components/PromptInput";
import StyleSelector from "../components/StyleSelector";
import Login from '../components/Login';
import { generateImage, saveToFavorites, queryJobStatus, fetchWithToken, generateSanaImage, querySanaJobStatus } from '../utils/api';
import SimpleModal from '../components/SimpleModal';
import PocketBase from 'pocketbase';

const pb = new PocketBase(process.env.NEXT_PUBLIC_API_ENDPOINT);


// 添加 UnsubscribeFunc 类型
type UnsubscribeFunc = () => void;

export default function Home() {
  const router = useRouter();
  const [isLoggedIn, setIsLoggedIn] = useState<boolean>(false);
  const [loginError, setLoginError] = useState<string>('');
  const [resultImage, setResultImage] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [progress, setProgress] = useState(0);
  const [isFavorited, setIsFavorited] = useState<boolean>(false);
  const [jobId, setJobId] = useState<string | null>(null);
  const [jobGpuPicId, setjobGpuPicId] = useState<string | null>(null);
  const [showSuccessMessage, setShowSuccessMessage] = useState<boolean>(false);
  const [dropdownOpen, setDropdownOpen] = useState(false);
  const [userBalance, setUserBalance] = useState<number | null>(null);
  const [subscriptionId, setSubscriptionId] = useState<UnsubscribeFunc | null>(null);
  const [showBalanceError, setShowBalanceError] = useState<boolean>(false);

  useEffect(() => {
    const token = localStorage.getItem('token');
    if (!token) {
      // 如果没有 token，重定向到登录页
      setIsLoggedIn(false);
      router.push('/login');
    } else {
      setIsLoggedIn(true); // 用户已登录
      fetchUserInfo(); // Fetch user info on login
    }
  }, [router]);

  //  fetchUserInfo 函数更新
  const fetchUserInfo = async () => {
    try {
      const user_id = localStorage.getItem('user_id');
      if (!user_id) {
        console.error('User ID is null or undefined');
        return;
      }
  
      // 获取初始用户数据
      const data = await fetchWithToken('/api/collections/users/records/' + user_id);
      setUserBalance(data.amount);
  
      // 订阅用户余额变化
      const unsubscribe = pb.collection('users').subscribe(user_id, (e) => {
        if (e.action === 'update') {
          console.log('User balance updated:', e.record.amount);
          setUserBalance(e.record.amount);
        }
      });
      
      setSubscriptionId(() => unsubscribe); // 存储取消订阅函数
    } catch (error) {
      console.error('Error fetching user info:', error);
    }
  };
  // handleLogout 函数更新
  const handleLogout = () => {
    // 取消订阅
    if (subscriptionId) {
      // subscriptionId();
    }
    localStorage.removeItem('token');
    localStorage.removeItem('user_id');
    router.push('/login');
  };

  const toggleDropdown = () => {
    setDropdownOpen(!dropdownOpen);
  };

  const handleGenerate = async (prompt: string, mode: string) => {
    // 检查用户余额
    if (userBalance === null || (mode === '混元' && userBalance < 5) || (mode === 'sana' && userBalance <= 0)) {
      setShowBalanceError(true); // 显示余额不足的弹窗
      return; // 结束函数
    }

    const token = localStorage.getItem('token');
    if (!token) {
      setLoginError('请先登录');
      router.push('/login');
      return;
    }

    console.log('生成图片:', prompt, '模式:', mode);
    setLoading(true);
    setProgress(0);
    setResultImage(null); // 重置结果图片
  
    // 确保 prompt 是字符串
    if (!prompt || prompt.trim() === '') {
      console.error('Prompt is empty or invalid');
      return; // 结束函数
    }
  
    let jobId: string | null = null;
    let jobGpuPicId: string | null = null;

    
  try {
    if (mode === '混元') {
      // 提交混元任务
      const { jobId: newJobId, jobGpuPicId: newJobGpuPicId } = await generateImage(prompt);
      jobId = newJobId;
      jobGpuPicId = newJobGpuPicId;
    } else if (mode === 'sana') {
      // 生成 session_hash
      const sessionHash = `local-${Math.random().toString(36).substring(2, 12)}`;
  
      // 使用 Promise.all 启动任务和进度条
      await Promise.all([
        (async () => {
          const { jobId: newJobId, jobGpuPicId: newJobGpuPicId } = await generateSanaImage(prompt, sessionHash);
          jobId = newJobId;
          jobGpuPicId = newJobGpuPicId;
          setJobId(jobId); // 设置 jobId
          setjobGpuPicId(jobGpuPicId);
        })(),
        (async () => {
          const totalDuration = 17000; // 17s
          const intervalDuration = 1000; // 每秒更新一次
          const totalSteps = totalDuration / intervalDuration; // 总步数
          let currentStep = 0;
  
          const interval = setInterval(() => {
            currentStep++;
            setProgress((currentStep / totalSteps) * 100); // 更新进度条
  
            if (currentStep >= totalSteps) {
              clearInterval(interval);
              setLoading(false);
              setTimeout(async () => {
                const statusData = await querySanaJobStatus(sessionHash);
                if (statusData.resultImage==="") {
                  statusData.resultImage="https://img2.baidu.com/it/u=1545125822,3988707860&fm=253&fmt=auto&app=138&f=JPEG?w=540&h=500"
                  setResultImage(statusData.resultImage)
                }else{
                  setResultImage(process.env.NEXT_PUBLIC_API_ENDPOINT + "/api/files/" + statusData.resultImage);
                }
              }, 2000); // 2秒后调用
            }
          }, intervalDuration);
        })(),
      ]);
  
      return; // 结束函数
    }
  
    setJobId(jobId); // 设置 jobId
    setjobGpuPicId(jobGpuPicId);
  
    // 启动进度条
    const interval = setInterval(async () => {
      if (jobId === null) {
        console.error('Job ID is null');
        clearInterval(interval);
        setLoading(false);
        return;
      }
      
      const statusData = await queryJobStatus(jobId);
      const jobStatus = statusData.jobStatusCode;
  
      if (jobStatus === '5') {
        clearInterval(interval);
        setLoading(false);
        console.log('处理完成:', statusData.resultImage[0]);
        if (statusData.resultImage[0]==="") {
          statusData.resultImage[0]="https://img2.baidu.com/it/u=1545125822,3988707860&fm=253&fmt=auto&app=138&f=JPEG?w=540&h=500"
        }
        setResultImage(statusData.resultImage[0]); // 设置生成的图片 URL  这里如果是空的，那么就用默认图片
      } else if (jobStatus === '4') {
        clearInterval(interval);
        setLoading(false);
        console.log('处理失败');
      } else {
        setProgress((prev) => Math.min(prev + 10, 100)); // 更新进度
      }
    }, 2000);
    } catch (error) {
      console.error('生成失败:', error);
      setLoading(false);
      setProgress(0);
      alert('生成失败，请稍后重试');
      return;

    }
  };
  

  const handleFavorite = async () => {
    if (resultImage && !isFavorited && jobId) {
      const formData = new FormData();
      let prompt: string;

      // 判断任务类型
      if (jobId.startsWith("local-")) {
        // 如果 jobId 以 "local-" 开头，说明是 sana 任务
        const sanaData = await fetchWithToken(`/api/collections/job_gpupic/records/${jobGpuPicId}`);
        prompt = sanaData.revisedPrompt;

      } else {
        const statusData = await queryJobStatus(jobId);
        prompt = statusData.revisedPrompt[0]; 
      }

      formData.append('sum_prompt', prompt);
      formData.append('job_id', jobId);
      
      // Ensure jobGpuPicId is not null before appending
      if (jobGpuPicId !== null) {
        formData.append('job_gpupic_id', jobGpuPicId);
      } else {
        console.error('jobGpuPicId is null');
        return; // Handle the null case, maybe show an error to the user
      }

      const user_id = localStorage.getItem('user_id');
      if (user_id) {
        formData.append('by_user', user_id);
      }

      try {
        await saveToFavorites(formData);
        setIsFavorited(true);
        setShowSuccessMessage(true);
      } catch (error) {
        console.error('Error saving to favorites:', error);
      }
    }
};


  const handleNavigateToProfile = () => {
    router.push('/profile'); // 跳转到个人中心页面
  };

  // 在组件卸载时取消订阅
  // useEffect(() => {
  //   return () => {
  //     if (subscriptionId) {
  //       subscriptionId();
  //     }
  //   };
  // }, [subscriptionId]);
  
  

  if (!isLoggedIn) {
    return <Login setLoginError={setLoginError} />;
  }

  return (
    <div className="flex flex-col lg:flex-row min-h-screen p-4 gap-4 relative">
      {loginError && <p className="text-red-500">{loginError}</p>}
      
      {/* 使用 SimpleModal 组件显示弹窗 */}
      <SimpleModal isOpen={showSuccessMessage} onClose={() => setShowSuccessMessage(false)} title="收藏成功！">
        <p className="text-sm text-gray-500">您的图片已成功收藏。</p>
      </SimpleModal>

      {/* 余额不足的弹窗 */}
      <SimpleModal isOpen={showBalanceError} onClose={() => setShowBalanceError(false)} title="余额不足">
        <p className="text-sm text-gray-500">您的余额不足，无法生成图片。</p>
      </SimpleModal>

      {/* 左侧图片展示区 */}
      <div className="relative w-full lg:w-1/2 bg-gray-100 dark:bg-gray-800 rounded-lg flex items-center justify-center min-h-[400px]">
        {resultImage ? (
          <>
            <img 
            src={resultImage} 
            alt="生成的图片" 
            className="w-full h-auto rounded-lg" 
          
            width={500} 
            height={300} 
            />
            <button 
              onClick={() => setResultImage(null)} 
              className="absolute bottom-4 right-4 bg-gradient-to-r from-purple-300 to-red-500 text-white rounded-lg px-4 py-2 shadow-lg hover:shadow-xl transition-transform transform hover:scale-105"
            >
              清空
            </button>
          </>
        ) : (
          <div className="text-center text-gray-500 dark:text-gray-400">
            生成的图片将在这里显示
          </div>
        )}
        {resultImage && !isFavorited && (
          <button 
            onClick={handleFavorite} 
            className="absolute bottom-4 left-4 bg-gradient-to-r from-purple-500 to-blue-500 text-white rounded-lg px-4 py-2 shadow-lg hover:shadow-xl transition-transform transform hover:scale-105"
          >
            收藏
          </button>
        )}
        
        {/* 个人中心按钮和下拉菜单 */}
        <div className="absolute top-4 right-4">
          <button 
            onClick={toggleDropdown} 
            className="bg-blue-500 text-white rounded-lg px-2 py-1 shadow-lg hover:shadow-xl transition-transform transform hover:scale-105"
          >
            个人中心
          </button>
          {dropdownOpen && (
            <div className="mt-1 w-32 bg-white rounded-lg shadow-lg z-10">
              <button 
                onClick={handleNavigateToProfile} 
                className="block px-2 py-1 text-gray-800 hover:bg-gray-200 w-full text-left text-sm"
              >
                个人中心
              </button>
              <button 
                onClick={handleLogout} 
                className="block px-2 py-1 text-gray-800 hover:bg-gray-200 w-full text-left text-sm"
              >
                退出登录
              </button>
            </div>
          )}
        </div>

        {/* User balance display */}
        {isLoggedIn && userBalance !== null && (
          <div className="absolute top-16 right-4 text-center" style={{ color: '#D6CDAF' }}>
            <div className="text-lg font-bold">可使用次数</div>
            <div className="text-4xl font-extrabold">{userBalance}</div>
          </div>
        )}
      </div>

      {/* 右侧控制面板 */}
      <div className="w-full lg:w-1/2 flex flex-col gap-4">
        {/* 右上方提示词输入区 */}
        <div className="h-[10%] bg-white dark:bg-gray-900 rounded-lg p-4 shadow-lg">
          <PromptInput 
            setResultImage={setResultImage} 
            setLoading={setLoading} 
            setProgress={setProgress} 
            loading={loading}
            handleGenerate={handleGenerate}
          />
          {loading && (
            <div className="relative w-full h-2 bg-gray-200 rounded mt-2">
              <div
                className="absolute h-full bg-purple-600 rounded"
                style={{ width: `${progress}%` }}
              />
            </div>
          )}
        </div>

        {/* 分割线 */}
        <div className="border-t border-gray-200 dark:border-gray-700 my-2"></div>

        {/* 右下方样式选择区 */}
        <div className="h-[80%] bg-white dark:bg-gray-900 rounded-lg p-4 shadow-lg">
          <StyleSelector />
        </div>
      </div>
    </div>
  );
}
